<template>
  <div class="home-page">
    <!-- 主标题区域 -->
    <div class="hero-section">
      <div class="hero-content">
        <h1 class="main-title">
          <span class="title-text">一句话</span>
          <span class="title-icon">🤖</span>
          <span class="title-text">呈所想</span>
        </h1>
        <p class="subtitle">与 AI 对话轻松创建应用和网站</p>

        <!-- 用户提示词输入框 -->
        <div class="prompt-input-section">
          <a-input-search
            v-model:value="promptText"
            placeholder="使用 NoCode 创建一个高效的小工具，程序计算..."
            size="large"
            class="prompt-input"
            :loading="creating"
            @search="handleCreateApp"
          >
            <template #enterButton>
              <a-button type="primary" size="large" :loading="creating">
                <template #icon>
                  <SendOutlined />
                </template>
                生成
              </a-button>
            </template>
          </a-input-search>
        </div>

        <!-- 快捷按钮 -->
        <div class="quick-buttons">
          <a-button class="quick-btn" @click="fillPrompt('设置风电首页')">设置风电首页</a-button>
          <a-button class="quick-btn" @click="fillPrompt('企业网站')">企业网站</a-button>
          <a-button class="quick-btn" @click="fillPrompt('电商运营后台')">电商运营后台</a-button>
          <a-button class="quick-btn" @click="fillPrompt('编程语言社区')">编程语言社区</a-button>
        </div>
      </div>
    </div>

    <!-- 我的作品区域 -->
    <div class="section my-apps-section">
      <div class="section-header">
        <h2 class="section-title">我的作品</h2>
        <a-button type="link" @click="viewAllMyApps">查看全部</a-button>
      </div>

      <div class="apps-grid">
        <div v-if="myApps.length === 0" class="empty-state">
          <a-empty description="暂无应用，快去创建一个吧！" />
        </div>
        <div v-else class="app-cards">
          <div v-for="app in myApps" :key="app.id" class="app-card" @click="goToApp(app.id)">
            <div class="app-cover">
              <img v-if="app.cover" :src="app.cover" :alt="app.appName" />
              <div v-else class="default-cover">
                <CodeOutlined />
              </div>
            </div>
            <div class="app-info">
              <h3 class="app-name">{{ app.appName }}</h3>
              <p class="app-time">创建于 {{ formatTime(app.createTime) }}</p>
            </div>
          </div>
        </div>
      </div>

      <!-- 分页 -->
      <div v-if="myApps.length > 0" class="pagination-wrapper">
        <a-pagination
          v-model:current="myAppsPagination.current"
          v-model:page-size="myAppsPagination.pageSize"
          :total="myAppsPagination.total"
          :show-size-changer="false"
          :show-quick-jumper="true"
          @change="loadMyApps"
        />
      </div>
    </div>

    <!-- 精选案例区域 -->
    <div class="section featured-apps-section">
      <div class="section-header">
        <h2 class="section-title">精选案例</h2>
        <a-button type="link" @click="viewAllFeaturedApps">查看全部</a-button>
      </div>

      <div class="apps-grid">
        <div v-if="featuredApps.length === 0" class="empty-state">
          <a-empty description="暂无精选应用" />
        </div>
        <div v-else class="app-cards featured-cards">
          <div
            v-for="app in featuredApps"
            :key="app.id"
            class="app-card featured-card"
            @click="goToApp(app.id)"
          >
            <div class="app-cover">
              <img v-if="app.cover" :src="app.cover" :alt="app.appName" />
              <div v-else class="default-cover featured-default">
                <StarOutlined />
              </div>
            </div>
            <div class="app-info">
              <h3 class="app-name">{{ app.appName }}</h3>
              <div class="app-meta">
                <span class="app-author">{{ app.user?.userName || 'NoCode 官方' }}</span>
                <span class="app-time">{{ formatTime(app.createTime) }}</span>
              </div>
            </div>
            <div class="featured-badge">
              <StarFilled />
            </div>
          </div>
        </div>
      </div>

      <!-- 分页 -->
      <div v-if="featuredApps.length > 0" class="pagination-wrapper">
        <a-pagination
          v-model:current="featuredAppsPagination.current"
          v-model:page-size="featuredAppsPagination.pageSize"
          :total="featuredAppsPagination.total"
          :show-size-changer="false"
          :show-quick-jumper="true"
          @change="loadFeaturedApps"
        />
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { message } from 'ant-design-vue'
import { SendOutlined, CodeOutlined, StarOutlined, StarFilled } from '@ant-design/icons-vue'
import { useLoginUserStore } from '@/stores/loginUser'
import { addApp, listMyAppVoByPage, listGoodAppVoByPage } from '@/api/appController'

const router = useRouter()
const loginUserStore = useLoginUserStore()

// 提示词输入
const promptText = ref('')
const creating = ref(false)

// 快捷按钮填充提示词
const fillPrompt = (template: string) => {
  const prompts = {
    设置风电首页:
      '使用 NoCode 创建一个风力发电企业的官方首页，包含公司介绍、产品展示、新闻动态和联系方式',
    企业网站:
      '使用 NoCode 创建一个现代化的企业官网，包含首页、关于我们、产品服务、新闻中心和联系我们页面',
    电商运营后台:
      '使用 NoCode 创建一个电商运营管理后台，包含商品管理、订单管理、用户管理和数据统计功能',
    编程语言社区:
      '使用 NoCode 创建一个编程语言学习社区，包含课程展示、讨论论坛、代码分享和在线编程功能',
  }
  promptText.value = prompts[template] || template
}

// 我的应用数据
const myApps = ref<API.AppVO[]>([])
const myAppsPagination = ref({
  current: 1,
  pageSize: 6,
  total: 0,
})

// 精选应用数据
const featuredApps = ref<API.AppVO[]>([])
const featuredAppsPagination = ref({
  current: 1,
  pageSize: 8,
  total: 0,
})

// 是否已登录
const isLoggedIn = computed(() => !!loginUserStore.loginUser.id)

// 创建应用
const handleCreateApp = async () => {
  if (!promptText.value.trim()) {
    message.warning('请输入应用描述')
    return
  }

  if (!isLoggedIn.value) {
    message.warning('请先登录')
    router.push('/user/login')
    return
  }

  creating.value = true
  try {
    const res = await addApp({ initPrompt: promptText.value.trim() })
    if (res.data.code === 0 && res.data.data) {
      message.success('应用创建成功，正在跳转...')
      // 跳转到对话页面
      router.push(`/app/chat/${res.data.data}`)
    } else {
      message.error(res.data.message || '创建失败')
    }
  } catch (error) {
    console.error('创建应用失败:', error)
    message.error('创建失败，请重试')
  } finally {
    creating.value = false
  }
}

// 加载我的应用
const loadMyApps = async (page = 1) => {
  if (!isLoggedIn.value) {
    myApps.value = []
    return
  }

  try {
    const res = await listMyAppVoByPage({
      pageNum: page,
      pageSize: myAppsPagination.value.pageSize,
      sortField: 'createTime',
      sortOrder: 'desc',
    })

    if (res.data.code === 0 && res.data.data) {
      myApps.value = res.data.data.records || []
      myAppsPagination.value = {
        current: page,
        pageSize: myAppsPagination.value.pageSize,
        total: res.data.data.totalRow || 0,
      }
    }
  } catch (error) {
    console.error('加载我的应用失败:', error)
  }
}

// 加载精选应用
const loadFeaturedApps = async (page = 1) => {
  try {
    const res = await listGoodAppVoByPage({
      pageNum: page,
      pageSize: featuredAppsPagination.value.pageSize,
      sortField: 'priority',
      sortOrder: 'desc',
    })

    if (res.data.code === 0 && res.data.data) {
      featuredApps.value = res.data.data.records || []
      featuredAppsPagination.value = {
        current: page,
        pageSize: featuredAppsPagination.value.pageSize,
        total: res.data.data.totalRow || 0,
      }
    }
  } catch (error) {
    console.error('加载精选应用失败:', error)
  }
}

// 跳转到应用详情
const goToApp = (appId: number) => {
  router.push(`/app/chat/${appId}`)
}

// 查看全部我的应用
const viewAllMyApps = () => {
  if (!isLoggedIn.value) {
    message.warning('请先登录')
    router.push('/user/login')
    return
  }
  // 这里可以跳转到我的应用管理页面
  router.push('/user/apps')
}

// 查看全部精选应用
const viewAllFeaturedApps = () => {
  router.push('/apps/featured')
}

// 格式化时间
const formatTime = (timeStr: string) => {
  if (!timeStr) return ''
  const date = new Date(timeStr)
  const now = new Date()
  const diff = now.getTime() - date.getTime()
  const days = Math.floor(diff / (1000 * 60 * 60 * 24))

  if (days === 0) {
    return '今天'
  } else if (days === 1) {
    return '昨天'
  } else if (days < 7) {
    return `${days}天前`
  } else {
    return date.toLocaleDateString()
  }
}

// 页面初始化
onMounted(() => {
  loadMyApps()
  loadFeaturedApps()
})
</script>

<style scoped>
.home-page {
  min-height: 100vh;
  background: linear-gradient(
    135deg,
    #4ade80 0%,
    #22c55e 25%,
    #16a34a 50%,
    #15803d 75%,
    #166534 100%
  );
}

/* 主标题区域 */
.hero-section {
  padding: 80px 20px 120px;
  text-align: center;
  background: linear-gradient(
    135deg,
    #4ade80 0%,
    #22c55e 25%,
    #16a34a 50%,
    #15803d 75%,
    #166534 100%
  );
  color: white;
  position: relative;
  overflow: hidden;
}

.hero-section::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100"><defs><pattern id="grain" width="100" height="100" patternUnits="userSpaceOnUse"><circle cx="50" cy="50" r="1" fill="%23ffffff" opacity="0.1"/></pattern></defs><rect width="100" height="100" fill="url(%23grain)"/></svg>')
    repeat;
  pointer-events: none;
}

.hero-content {
  max-width: 800px;
  margin: 0 auto;
  position: relative;
  z-index: 1;
}

.main-title {
  font-size: 3.5rem;
  font-weight: 700;
  margin-bottom: 20px;
  line-height: 1.2;
}

.title-text {
  background: linear-gradient(45deg, #fff, #f0fff4);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
}

.title-icon {
  font-size: 3rem;
  margin: 0 10px;
  display: inline-block;
  animation: bounce 2s infinite;
}

@keyframes bounce {
  0%,
  20%,
  50%,
  80%,
  100% {
    transform: translateY(0);
  }
  40% {
    transform: translateY(-10px);
  }
  60% {
    transform: translateY(-5px);
  }
}

.subtitle {
  font-size: 1.2rem;
  margin-bottom: 40px;
  opacity: 0.9;
}

.prompt-input-section {
  margin-bottom: 30px;
}

.prompt-input {
  max-width: 600px;
  margin: 0 auto;
}

.prompt-input :deep(.ant-input) {
  border-radius: 25px;
  padding: 12px 20px;
  font-size: 16px;
  border: 2px solid rgba(255, 255, 255, 0.3);
  background: rgba(255, 255, 255, 0.1);
  color: white;
  backdrop-filter: blur(10px);
}

.prompt-input :deep(.ant-input::placeholder) {
  color: rgba(255, 255, 255, 0.7);
}

.prompt-input :deep(.ant-input-search-button) {
  border-radius: 0 25px 25px 0;
  border: none;
  background: linear-gradient(45deg, #ff6b6b, #ee5a24);
  height: 48px;
}

.quick-buttons {
  display: flex;
  gap: 12px;
  justify-content: center;
  flex-wrap: wrap;
}

.quick-btn {
  border-radius: 20px;
  border: 1px solid rgba(255, 255, 255, 0.3);
  background: rgba(255, 255, 255, 0.1);
  color: white;
  backdrop-filter: blur(10px);
  transition: all 0.3s ease;
  cursor: pointer;
}

.quick-btn:hover {
  background: rgba(255, 255, 255, 0.2);
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
  color: white;
  border-color: rgba(255, 255, 255, 0.5);
}

/* 内容区域 */
.section {
  padding: 60px 20px;
  max-width: 1200px;
  margin: 0 auto;
  background: white;
  margin-top: -60px;
  border-radius: 20px 20px 0 0;
  position: relative;
  z-index: 2;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 40px;
}

.section-title {
  font-size: 2rem;
  font-weight: 600;
  color: #2c3e50;
  margin: 0;
}

.apps-grid {
  margin-bottom: 40px;
}

.app-cards {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 24px;
}

.app-card {
  background: white;
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
  cursor: pointer;
  position: relative;
}

.app-card:hover {
  transform: translateY(-4px);
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.15);
}

.app-cover {
  height: 160px;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;
  overflow: hidden;
}

.app-cover img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.default-cover {
  font-size: 3rem;
  color: #8c9eff;
}

.featured-default {
  color: #ffd700;
}

.app-info {
  padding: 20px;
}

.app-name {
  font-size: 1.1rem;
  font-weight: 600;
  color: #2c3e50;
  margin: 0 0 8px 0;
  line-height: 1.4;
}

.app-time {
  color: #7f8c8d;
  font-size: 0.9rem;
  margin: 0;
}

.app-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 0.9rem;
  color: #7f8c8d;
}

.app-author {
  font-weight: 500;
  color: #3498db;
}

.featured-card {
  border: 2px solid #ffd700;
}

.featured-badge {
  position: absolute;
  top: 12px;
  right: 12px;
  background: #ffd700;
  color: white;
  border-radius: 50%;
  width: 32px;
  height: 32px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 14px;
}

.my-apps-section {
  background: #f8f9fa;
}

.featured-apps-section {
  background: white;
  margin-top: 0;
  border-radius: 0;
}

.empty-state {
  text-align: center;
  padding: 60px 20px;
}

.pagination-wrapper {
  display: flex;
  justify-content: center;
  margin-top: 40px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .main-title {
    font-size: 2.5rem;
  }

  .hero-section {
    padding: 60px 20px 80px;
  }

  .section {
    padding: 40px 16px;
    margin-top: -40px;
  }

  .section-header {
    flex-direction: column;
    gap: 16px;
    align-items: flex-start;
  }

  .app-cards {
    grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
    gap: 16px;
  }

  .quick-buttons {
    gap: 8px;
  }

  .quick-btn {
    font-size: 0.9rem;
    padding: 6px 12px;
  }
}

@media (max-width: 480px) {
  .main-title {
    font-size: 2rem;
  }

  .app-cards {
    grid-template-columns: 1fr;
  }

  .prompt-input :deep(.ant-input) {
    font-size: 14px;
    padding: 10px 16px;
  }
}
</style>
